package com.yfq.springframework.beans.support;

import com.yfq.springframework.beans.config.BeanDefinition;
import com.yfq.springframework.beans.config.BeanReference;
import com.yfq.springframework.exception.BeansException;
import com.yfq.springframework.util.BeanUtils;

import java.lang.reflect.Constructor;

/**
 * @author 姚凤桥
 * @date 2022/11/22 16:06
 * @description
 */
public abstract class AbstractAutowiredCapableBeanFactory extends AbstractBeanFactory {
    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object... args) {
        Constructor<?> constructorToUse = null;
        Constructor<?>[] declaredConstructors = beanDefinition.getBeanClass().getDeclaredConstructors();
        for (Constructor<?> constructor : declaredConstructors) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            if (args != null && parameterTypes.length == args.length) {
                constructorToUse = constructor;
                break;
            }
        }

        //创建bean
        Object bean = instantiationStrategy.instantiate(beanName, beanDefinition, constructorToUse, args);

        //依赖注入
        applyPropertyValues(beanName, bean, beanDefinition);

        //将bean添加到容器
        registerSingletonBean(beanName, bean);
        return bean;
    }

    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }

                BeanUtils.setFieldValue(bean, name, value);
            }
        } catch (Exception e) {
            throw new BeansException("名为[" + beanName + "]的bean依赖注入错误！");
        }
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
